using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using ExamPaperEditingSystem.Models;

namespace ExamPaperEditingSystem.Services
{
    public class ExamPaperService : IExamPaperService
    {
        private readonly List<ExamPaper> _examPapers;
        private readonly string _dataPath;
        private readonly string _exportPath;

        public ExamPaperService()
        {
            _examPapers = new List<ExamPaper>();
            _dataPath = Path.Combine(Environment.CurrentDirectory, "Vector Knowledge Base", "ExamPapers");
            _exportPath = Path.Combine(Environment.CurrentDirectory, "Exam paper file");
            
            if (!Directory.Exists(_dataPath))
            {
                Directory.CreateDirectory(_dataPath);
            }
            
            if (!Directory.Exists(_exportPath))
            {
                Directory.CreateDirectory(_exportPath);
            }
        }

        public Task<ExamPaper> CreateExamPaperAsync(string title, string subject, string grade)
        {
            var examPaper = new ExamPaper
            {
                Title = title,
                Subject = subject,
                Grade = grade
            };

            _examPapers.Add(examPaper);
            return Task.FromResult(examPaper);
        }

        public Task<List<ExamPaper>> GetExamPapersAsync()
        {
            return Task.FromResult(_examPapers.ToList());
        }

        public Task<ExamPaper?> GetExamPaperAsync(string id)
        {
            var examPaper = _examPapers.FirstOrDefault(ep => ep.Id == id);
            return Task.FromResult(examPaper);
        }

        public async Task SaveExamPaperAsync(ExamPaper examPaper)
        {
            var existingPaper = _examPapers.FirstOrDefault(ep => ep.Id == examPaper.Id);
            if (existingPaper == null)
            {
                _examPapers.Add(examPaper);
            }
            else
            {
                var index = _examPapers.IndexOf(existingPaper);
                _examPapers[index] = examPaper;
            }

            var filePath = Path.Combine(_dataPath, $"{examPaper.Id}.json");
            var json = JsonSerializer.Serialize(examPaper, new JsonSerializerOptions
            {
                WriteIndented = true,
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase
            });
            
            await File.WriteAllTextAsync(filePath, json);
        }

        public async Task DeleteExamPaperAsync(string id)
        {
            var examPaper = _examPapers.FirstOrDefault(ep => ep.Id == id);
            if (examPaper != null)
            {
                _examPapers.Remove(examPaper);
                
                await Task.Run(() =>
                {
                    var filePath = Path.Combine(_dataPath, $"{id}.json");
                    if (File.Exists(filePath))
                    {
                        File.Delete(filePath);
                    }
                });
            }
        }

        public async Task<string> ExportToWordAsync(ExamPaper examPaper)
        {
            var fileName = $"{examPaper.Title}_{DateTime.Now:yyyyMMdd_HHmmss}.docx";
            var filePath = Path.Combine(_exportPath, fileName);

            await Task.Run(() =>
            {
                using var document = WordprocessingDocument.Create(filePath, WordprocessingDocumentType.Document);
            var mainPart = document.AddMainDocumentPart();
            mainPart.Document = new Document();
            var body = mainPart.Document.AppendChild(new Body());

            // 添加标题
            var titleParagraph = new Paragraph();
            var titleRun = new Run();
            var titleText = new Text(examPaper.Title);
            titleRun.Append(titleText);
            titleParagraph.Append(titleRun);
            
            // 设置标题样式
            var titleProperties = new ParagraphProperties();
            var titleJustification = new Justification() { Val = JustificationValues.Center };
            titleProperties.Append(titleJustification);
            titleParagraph.PrependChild(titleProperties);
            
            body.Append(titleParagraph);

            // 添加考试信息
            var infoParagraph = new Paragraph();
            var infoRun = new Run();
            var infoText = new Text($"科目：{examPaper.Subject}    年级：{examPaper.Grade}    总分：{examPaper.TotalScore}分    时间：{examPaper.Duration.TotalMinutes}分钟");
            infoRun.Append(infoText);
            infoParagraph.Append(infoRun);
            body.Append(infoParagraph);

            // 添加空行
            body.Append(new Paragraph());

            // 添加题目
            for (int i = 0; i < examPaper.Questions.Count; i++)
            {
                var question = examPaper.Questions[i];
                
                // 题目内容
                var questionParagraph = new Paragraph();
                var questionRun = new Run();
                var questionText = new Text($"{i + 1}. {question.Content} ({question.Score}分)");
                questionRun.Append(questionText);
                questionParagraph.Append(questionRun);
                body.Append(questionParagraph);

                // 选项（如果是选择题）
                if (question.Type == QuestionType.SingleChoice || question.Type == QuestionType.MultipleChoice)
                {
                    for (int j = 0; j < question.Options.Count; j++)
                    {
                        var optionParagraph = new Paragraph();
                        var optionRun = new Run();
                        var optionText = new Text($"   {(char)('A' + j)}. {question.Options[j]}");
                        optionRun.Append(optionText);
                        optionParagraph.Append(optionRun);
                        body.Append(optionParagraph);
                    }
                }

                // 添加答题空间
                if (question.Type == QuestionType.FillInBlank || question.Type == QuestionType.ShortAnswer || question.Type == QuestionType.Essay)
                {
                    for (int k = 0; k < 3; k++)
                    {
                        var spaceParagraph = new Paragraph();
                        var spaceRun = new Run();
                        var spaceText = new Text("_".PadRight(50, '_'));
                        spaceRun.Append(spaceText);
                        spaceParagraph.Append(spaceRun);
                        body.Append(spaceParagraph);
                    }
                }

                // 添加空行
                body.Append(new Paragraph());
            }

                document.Save();
            });
            
            return filePath;
        }

        public async Task<ExamPaper> ImportFromWordAsync(string filePath)
        {
            return await Task.Run(() =>
            {
                // 简化的Word导入实现
                var examPaper = new ExamPaper
                {
                    Title = Path.GetFileNameWithoutExtension(filePath),
                    Subject = "未知",
                    Grade = "未知"
                };

                using var document = WordprocessingDocument.Open(filePath, false);
            var body = document.MainDocumentPart?.Document?.Body;
            
            if (body != null)
            {
                var paragraphs = body.Elements<Paragraph>().ToList();
                var currentQuestion = new ExamQuestion();
                var questionNumber = 1;

                foreach (var paragraph in paragraphs)
                {
                    var text = paragraph.InnerText.Trim();
                    if (string.IsNullOrEmpty(text))
                        continue;

                    // 简单的题目识别逻辑
                    if (text.StartsWith($"{questionNumber}."))
                    {
                        if (!string.IsNullOrEmpty(currentQuestion.Content))
                        {
                            examPaper.Questions.Add(currentQuestion);
                        }
                        
                        currentQuestion = new ExamQuestion
                        {
                            Content = text[(text.IndexOf('.') + 1)..].Trim(),
                            Type = QuestionType.ShortAnswer,
                            Score = 5
                        };
                        questionNumber++;
                    }
                }

                if (!string.IsNullOrEmpty(currentQuestion.Content))
                {
                    examPaper.Questions.Add(currentQuestion);
                }
            }

                return examPaper;
            });
        }

        public Task<string> FormatExamPaperForCopyAsync(ExamPaper examPaper)
        {
            var sb = new StringBuilder();
            
            // 标题
            sb.AppendLine(examPaper.Title);
            sb.AppendLine(new string('=', examPaper.Title.Length));
            sb.AppendLine();
            
            // 考试信息
            sb.AppendLine($"科目：{examPaper.Subject}");
            sb.AppendLine($"年级：{examPaper.Grade}");
            sb.AppendLine($"总分：{examPaper.TotalScore}分");
            sb.AppendLine($"考试时间：{examPaper.Duration.TotalMinutes}分钟");
            sb.AppendLine();
            sb.AppendLine(new string('-', 50));
            sb.AppendLine();
            
            // 题目
            for (int i = 0; i < examPaper.Questions.Count; i++)
            {
                var question = examPaper.Questions[i];
                sb.AppendLine($"{i + 1}. {question.Content} ({question.Score}分)");
                
                // 选项
                if (question.Type == QuestionType.SingleChoice || question.Type == QuestionType.MultipleChoice)
                {
                    for (int j = 0; j < question.Options.Count; j++)
                    {
                        sb.AppendLine($"   {(char)('A' + j)}. {question.Options[j]}");
                    }
                }
                
                sb.AppendLine();
            }
            
            return Task.FromResult(sb.ToString());
        }

        public async Task LoadExamPapersAsync()
        {
            _examPapers.Clear();
            
            if (!Directory.Exists(_dataPath))
            {
                return;
            }

            var files = Directory.GetFiles(_dataPath, "*.json");
            foreach (var file in files)
            {
                try
                {
                    var json = await File.ReadAllTextAsync(file);
                    var examPaper = JsonSerializer.Deserialize<ExamPaper>(json, new JsonSerializerOptions
                    {
                        PropertyNamingPolicy = JsonNamingPolicy.CamelCase
                    });
                    
                    if (examPaper != null)
                    {
                        _examPapers.Add(examPaper);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"加载试卷文件 {file} 失败: {ex.Message}");
                }
            }
        }

        public async Task<List<ExamPaper>> GetAllExamPapersAsync()
        {
            var examPapers = new List<ExamPaper>();
            var examPaperDirectory = Path.Combine(Environment.CurrentDirectory, "Exam paper file");
            
            if (Directory.Exists(examPaperDirectory))
            {
                var files = Directory.GetFiles(examPaperDirectory, "*.json");
                foreach (var file in files)
                {
                    try
                    {
                        var json = await File.ReadAllTextAsync(file);
                        var examPaper = JsonSerializer.Deserialize<ExamPaper>(json);
                        if (examPaper != null)
                        {
                            examPapers.Add(examPaper);
                        }
                    }
                    catch (Exception ex)
                    {
                        // 记录错误但继续处理其他文件
                        Console.WriteLine($"加载试卷文件失败 {file}: {ex.Message}");
                    }
                }
            }
            
            return examPapers;
        }
    }
}